from flask import Blueprint, request, abort, current_app, g, render_template, session, json
# from urllib.parse import urlencode

from werkzeug.security import check_password_hash, generate_password_hash

from flask_jsontools import jsonapi

from .decorator import valid_header, param, RequestBody

from . import alipay_oauth

from .models import *

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login/<int:id>', methods=('GET', 'POST', 'DELETE'))
# @param('name', required=True)
@RequestBody('user', param_type=User)
# @valid_header('content_type', header_value='application/json', methods=('POST', ), fuzzy=False)
@jsonapi
def login(id, user):
    if (request.method == 'POST'):
        return user

@bp.route('/get_token')
@param('auth_code', required=True, methods=('GET',))
# @param('oauth_service', required=True, methods=('GET',))
@jsonapi
def get_token(auth_code):
    # if oauth_service == 'ALIPAY':
    if alipay_oauth.get_access_token(auth_code):
        return session['user_id']
    return ''

@bp.route('/ali_login')
def to_ali_login():
    return render_template('ali_login.html',
           url='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='
               + alipay_oauth.app_id
               + '&scope=auth_user&redirect_uri='
               + 'http%3a%2f%2ftimemgr.liesly.top%3a5000%2fauth%2fget_token'
               + '&state=init')

@bp.route('/logout', methods=('GET',))
@jsonapi
def logout():
    return User.query.all()

@bp.route('/register', methods=('GET', 'POST'))
def register():
    ...

# def updateInfo():
